package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bean.JsApiTicket;
import com.bean.WeixinToken;
import com.scan.config.SysConf;
import com.scan.utils.CacheUtil;


/**
 * Created by tancw on 2017/2/13.
 */

public class TokenUtil {

    private static final String APPID = SysConf.get("weixin.appID");
    private static final String APP_SEC = SysConf.get("weixin.appsecret");


    public static String getJsApiTicket() {
        String key = "jsApi" + APPID;
        JsApiTicket apiTicket = (JsApiTicket) CacheUtil.get(key);
        String jsonStr = null;

        if (apiTicket == null || !apiTicket.isAva()) {
            String e = getToken(false);
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + e + "&type=jsapi";
            jsonStr = HttpUtil.get(url);
            JSONObject object = JSON.parseObject(jsonStr);
            String ticket = object.getString("ticket");
            if (ticket != null) {
                apiTicket = new JsApiTicket();
                apiTicket.setTicket(ticket);
                CacheUtil.add(key, apiTicket, 7200L);
            }
        }
        return apiTicket != null ? apiTicket.getTicket() : null;
    }

    public static WeixinToken initToken(boolean fresh) {
        WeixinToken token = (WeixinToken) CacheUtil.get(APPID);
        if (!fresh && token != null && token.isAva()) {
            return token;
        }
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APP_SEC);
        String jsonStr = HttpUtil.get(url);
        JSONObject object = JSON.parseObject(jsonStr);
        String access_token = object.getString("access_token");
        if (access_token != null) {
            token = new WeixinToken();
            token.setAccess_token(access_token);
            CacheUtil.add(APPID, token, 7200L);
        }
        return token;
    }

    private static String getToken(boolean fresh) {
        WeixinToken token = initToken(fresh);
        return token != null ? token.getAccess_token() : null;
    }

}
